<template>
  <div>
    <canvas id="renderCanvas"></canvas>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue';
import * as BABYLON from '@babylonjs/core';
import '@babylonjs/loaders/glTF'; // 引入 GLTF 加载器
onMounted(() => {
  const canvas = document.getElementById('renderCanvas');
  const engine = new BABYLON.Engine(canvas, true);
  const createScene = () => {
    const scene = new BABYLON.Scene(engine);
    const camera = new BABYLON.ArcRotateCamera("Camera", Math.PI / 2, Math.PI / 2, 2, BABYLON.Vector3.Zero(), scene);
    camera.attachControl(canvas, true);
    const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(1, 1, 0), scene);
    // 定义更曲折的曲线
    var points = [
      new BABYLON.Vector3(-5, 0, 0),
      new BABYLON.Vector3(-2, 0, 2),
      new BABYLON.Vector3(2, 0, -2),
      new BABYLON.Vector3(5, 0, 0)
    ];



    const path3d = new BABYLON.Path3D(BABYLON.Curve3.CreateCatmullRomSpline(
        points,
        100,
        false
    ).getPoints());

    let pointsNew=[];
    let qiexian=[];

    for(let i=0;i<1;i+=0.01){
      pointsNew.push(path3d.getPointAt(i));
      qiexian.push(path3d.getTangentAt(i).normalize());
    }


    console.log(qiexian)
    //

    for (let i = 0; i <pointsNew.length; i++) {
      if(i%2==0){
        const box = BABYLON.MeshBuilder.CreateBox("box"+i, { size: 0.1 }, scene);
        box.position=pointsNew[i];
        box.rotation.y=Math.atan2(qiexian[i+1].x, qiexian[i+1].z);

      }
    }


    return scene;
  };

  const scene = createScene();

  const runRenderLoop = () => {
    engine.runRenderLoop(() => {
      scene.render();
    });
  };

  runRenderLoop();

  onUnmounted(() => {
    engine.dispose();
  });
});

</script>

<style scoped>
#renderCanvas {
  width: 100%;
  height: 100vh;
}
</style>